package com.zs.myorm.framework.core.method.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.zs.myorm.framework.core.annotation.Colunm;
import com.zs.myorm.framework.core.annotation.Id;
import com.zs.myorm.framework.core.annotation.TableName;
import com.zs.myorm.framework.core.execute.ISqlExecute;
import com.zs.myorm.framework.core.method.IMethodHandler;

public class FindAllMethodHandlerImpl implements IMethodHandler {
	private ISqlExecute sqlExecute;
	private final String methodName = "findAll";
	public String getMethodName() {
		return this.methodName ;
	}
	public void setSqlExecute(ISqlExecute sqlExecute) {
		this.sqlExecute = sqlExecute;
	}

	@Override
	public Object invoke(Class<?> beanClass, Method method, Object[] args) throws Exception {
			String tableName = null;
			List<String> ids = null;
			List<String> c = null;
			if (beanClass != null) {
				TableName annotation = beanClass.getAnnotation(TableName.class);
				tableName = annotation.value();
				Field[] declaredFields = beanClass.getDeclaredFields();
				ids = new ArrayList<String>();
				c = new ArrayList<String>();
				for (Field f : declaredFields) {
					Id id = f.getAnnotation(Id.class);
					if (id != null) {
						String value = id.value();
						if (value == null || value.isEmpty()) {
							value = f.getName();
						}
						ids.add(value);
					} else {
						Colunm col = f.getAnnotation(Colunm.class);
						if (col != null) {
							String value = col.value();
							if (value == null || value.isEmpty()) {
								value = f.getName();
							}
							c.add(value);
						}
					}
				}
			}
			
			
			String sql = "select * from " + tableName + " ";
			List<Map<String, Object>> select = this.sqlExecute.select(sql);
			List list = new ArrayList();
			for (Map<String, Object> map : select) {
				Object obj = beanClass.newInstance();
				Field[] declaredFields = beanClass.getDeclaredFields();
				for (Field f : declaredFields) {
					Id id = f.getAnnotation(Id.class);
					String value = null;
					if (id != null) {
						value = id.value();
						if (value == null || value.isEmpty()) {
							value = f.getName();
						}

					} else {
						Colunm col = f.getAnnotation(Colunm.class);
						if (col != null) {
							value = col.value();
							if (value == null || value.isEmpty()) {
								value = f.getName();
							}
							c.add(value);
						}
					}
					Object va = map.get(value);
					f.setAccessible(true);
					f.set(obj, va);
				}
				list.add(obj);
			}
			return list;
		
	}

}
